package com.itheima.jobs;

import com.itheima.constant.RedisConstant;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 自定义Job，实现定时清理垃圾图片
 */
public class ClearImgJob {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void clearImg() {
        //根据Redis中保存的两个set集合进行差值计算，获得垃圾图片名称集合
        Set<String> set = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        if (set != null && set.size() != 0) {
            for (String picName : set) {
                //删除七牛云服务器上的图片
                QiniuUtils.deleteFileFromQiniu(picName);
                System.out.println("清除成功");
                //从Redis集合中删除图片名称
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES, picName);
            }
        } else {
            System.out.println("没有垃圾图片，不用清除");
        }
    }

    public void clearOrderSetting(){
        Date date = new Date();
        List<OrderSetting> orderSettings = jdbcTemplate.query("select * from t_ordersetting where orderDate < ?;", new BeanPropertyRowMapper<>(OrderSetting.class), date);
        if (orderSettings != null && orderSettings.size() > 0){
            jdbcTemplate.update("delete from t_ordersetting where orderDate < ?", date);
            System.out.println("删除成功");
        }else {
            System.out.println("没有过期数据不需要清除");
        }
    }
}
